/**
 * Copyright 2008 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var url_tmpl = "http://code.google.com/p/%PROJECT%/source/list";
var title_tmpl = "%PROJECT% changes";
var feed_tmpl = "http://code.google.com/feeds/p/%PROJECT%/svnchanges/basic?path=%PATH%"
var row_tmpl = "<tr><td valign='top' style='border-bottom: 1px solid #BBBBBB;'><a href='%LINK%' target='_blank'>%REVISION%</a></td><td valign='top' style='border-bottom: 1px solid #BBBBBB;'>%TITLE%</td></tr>";

var prefs_obj = new gadgets.Prefs();  // Our prefs object
var projectName_str = "";             // For our projectName, required by common js
var currentPage_num = 1;              // For paging tracking
var feedURL_str = "";                 // Our feed
var path_str = prefs_obj.getString("path");  // The path to get from the feed

/**
 * Unlike the scraping gadgets, this function doesn't actually render anything.  Rather,
 * it asks the API to get a feed.  <code>renderCallback</code> is in charge of rendering.
 *
 * @param response_str  The page retrieved by <code>init</code>, unused.
 */
function render(responseText) {
  feedURL_str = feed_tmpl.replace("%PROJECT%", _hesc(projectName_str)).replace("%PATH%", _hesc(path_str));

  // Get the feed
  fetchAsFeed(feedURL_str, renderCallback, 16);
}

/**
 * Actually render the content off the feed.
 *
 * @param feed  The JSON feed.
 */
function renderCallback(feed) {
  var content_str = "";

  // Actually print the table
  if (feed.data) {
    content_str += "<center><table cellspacing='0' cellpadding='0' width='100%' id='#resultstable'>";
    var title_str = "";
    var revision_str = "";
    var titleEnd_num;
    var totalPages_num = Math.ceil(feed.data.Entry.length / 5);      // Get the number of pages
    totalPages_num = Math.min(totalPages_num, 3); // Restrict pages to 3

    // We ask for 16 entries, only to see if there are more than 15.  If so, this will get
    // passed to the paging function.
    var morePages_bool = feed.data.Entry.length > 15;

    // Start at the current page as multiplied by our max per page (5)
    var start_num = (currentPage_num - 1) * 5;

    // Restrict the stop point to a max of five, less if at the end of the feed
    var stop_num = Math.min(start_num + 5, feed.data.Entry.length);

    for (var i = start_num; i < stop_num; i++) {
      title_str = feed.data.Entry[i].Title;
      titleEnd_num = title_str.search(":");
      revision_str = "r" + title_str.substring(9, titleEnd_num);
      title_str = title_str.substring(titleEnd_num +2, title_str.length);
      title_str = ellipsify(title_str, 100);

      // Build row and cat to content_str
      content_str += row_tmpl.replace("%REVISION%", _hesc(revision_str))
                             .replace("%TITLE%", _hesc(title_str))
                             .replace("%LINK%", _hesc(feed.data.Entry[i].Link));
    }

    // End the table, print the paging, end the centered content
    content_str += "</table>";
    content_str += generatePaging(totalPages_num, currentPage_num, morePages_bool, feed.data.Entry.length);
    content_str += "</center>";
  } else {
    content_str += "No changes could be found.";
  }

  // Write the data to DOM
  $("#content_div").html(content_str);

  // Add some jQuery events for paging
  addPagingEvents(pagingCallback);

  // Adjust the height of this frame based on content
  adjustIFrameHeight();
}

/**
 * Event handler for paging links.
 *
 * @param page_num  The page number or global flag for <code>PAGE_NEXT</code>,
 *                  <code>PAGE_PREV</code>, or <code>PAGE_MORE</code>.
 */
function pagingCallback(page_num) {

  if (page_num == PAGE_MORE) {
    window.open(url_tmpl.replace("%PROJECT%", _hesc(projectName_str)), "_blank");
    return;
  }

  if (page_num == PAGE_PREV) {
    currentPage_num--;
  } else if (page_num == PAGE_NEXT) {
    currentPage_num++;
  } else {
    currentPage_num = page_num;
  }

  fetchAsFeed(feedURL_str, renderCallback, 16);
}

gadgets.util.registerOnLoadHandler(init);
